import axios from "axios";
import { MessageBox, Message } from "element-ui";
import router from "../router/index";
// import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL: "/cloud-admin", // url = base url + request url 修改当前访问地址
  withCredentials: true, // send cookies when cross-domain requests
  timeout: process.env.NODE_ENV === "development" ? 0 : 10000
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
      config.headers["token"] = getToken();
    // }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.data.success) {
      return response;
    }

    if (response.data.type == 2) {
      router.push("login");
      // MessageBox.confirm(
      //   "您还未登录或登录状态已过期，请重新登录或留在该页面，或者重新登录",
      //   "系统提示",
      //   {
      //     confirmButtonText: "重新登录",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }
      // ).then(() => {
      //   router.push("login");
      // });
      return;
    }

    if (response.data.type == 3) {
      router.push("login");
      // MessageBox.confirm(
      //   "操作权限，请分配权限后重新登录或留在该页面",
      //   "系统提示",
      //   {
      //     confirmButtonText: "重新登录",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }
      // ).then(() => {
      //   router.push("login");
      // });
      return;
    }

    if (response.data.type == 1||response.data.type == 4) {
      Message({
        showClose: true,
        message: response.data.message
      });
      return response;
    }

    return response;
  },
  error => {
    console.log(error);
    // Message.error("无法访问服务器");
    return error;
  }
);

export default service;
